"""
需要导入第三方模块
cmd控制台输入以下命令并执行：
pip install matplotlib
pip install numpy
"""
import matplotlib.pyplot as plt
import numpy as np
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False    # 用来正常显示负号

import matplotlib.dates as mdates
from datetime import datetime, timedelta

# 生成模拟股票数据
np.random.seed(42)
start_date = datetime(2022, 1, 1)
dates = [start_date + timedelta(days=i) for i in range(100)]
price = 100 + np.cumsum(np.random.normal(0, 1, 100))
volume = np.random.randint(1000, 5000, 100)

# 创建图表
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), sharex=True,
                              gridspec_kw={'height_ratios': [3, 1]})

# 绘制股票价格
ax1.plot(dates, price, 'b-', linewidth=1.5)
ax1.set_title('股票价格与交易量', fontsize=16)
ax1.set_ylabel('价格', fontsize=12)
ax1.grid(True, linestyle='--', alpha=0.7)

# 添加移动平均线
window = 5
ma = np.convolve(price, np.ones(window)/window, mode='valid')
ma_dates = dates[window-1:]
ax1.plot(ma_dates, ma, 'r-', linewidth=1.5, label=f'{window}日移动平均线')
ax1.legend()

# 绘制交易量
ax2.bar(dates, volume, color='g', alpha=0.5)
ax2.set_ylabel('交易量', fontsize=12)
ax2.set_xlabel('日期', fontsize=12)
ax2.grid(True, linestyle='--', alpha=0.7)

# 格式化日期
date_format = mdates.DateFormatter('%Y-%m-%d')
ax2.xaxis.set_major_formatter(date_format)
ax2.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))
plt.xticks(rotation=45)

plt.tight_layout()
plt.show()